package com.holdtime.jtt809dataservice.client.handler;

import com.holdtime.jtt809dataservice.common.NettyCommon;
import com.holdtime.jtt809dataservice.common.domain.ChannelHandlerContextManager;
import com.holdtime.jtt809dataservice.common.event.ClientMessageReceiveEvent;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.Attribute;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import protocol.jtt809.JTT809Packet;
import protocol.jtt809.JTT809Util;
import protocol.jtt809.ProtocolJT809;
import protocol.jtt809.body.RawBody;

import java.net.InetSocketAddress;

/**
 * author: sunwei
 * Date: 2025/3/18 11:58
 * Description:
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class SubordinatePlatformServerHandler extends ChannelInboundHandlerAdapter {
    @Resource
    private ApplicationContext context;
    @Resource
    private ProtocolJT809 protocolJT809;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof JTT809Packet) {
            JTT809Packet<RawBody> packet = (JTT809Packet<RawBody>) msg;
            //验证校验码
            if (packet.checkCrcCode()) {
                log.info("收到上级平台从链路809数据:{}", JTT809Util.antisense(packet.array()));
                Attribute<String> attr = ctx.channel().attr(NettyCommon.clientSubNumberKey);
                String number = attr.get();
                if (number == null) {
                    number = String.valueOf(packet.getMsgGnsscenterid());
                    attr.set(number);
                    log.debug("JTT809-client连接" + ctx.channel().remoteAddress().toString()
                            + "=>" + number);
                }
                ChannelHandlerContextManager.getCurrent().putClientSub(number, ctx);
                context.publishEvent(new ClientMessageReceiveEvent(packet, ctx));
            }
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        if (!ctx.channel().isActive()) {
            Attribute<String> attr = ctx.channel().attr(NettyCommon.subNumberKey);
            log.debug("JTT809-Client-Sub断开" + insocket.toString() + "=>" + attr.get());
            if (attr != null && attr.get() != null) {
                ChannelHandlerContext channelHandlerContext = ChannelHandlerContextManager
                        .getCurrent().getClientSub(attr.get());
                if (channelHandlerContext == ctx) {
                    ChannelHandlerContextManager.getCurrent().removeClientSub(attr.get());
                }
            }
        }
    }
}
